﻿using AegisImplicitMail;
using Jcex.Service.Mail.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using RazorEngine;
using RazorEngine.Templating;

namespace Jcex.Service.Mail.Controllers
{
    /// <summary>
    /// 电子邮件发送接口
    /// </summary>
    public class MailController : ApiController
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailContent">mail body content</param>
        /// <returns>接口响应</returns>
        /// 



        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult Send(EmailData mail)
        {
            string template = "Hello @Model.Name, welcome to RazorEngine!";

            var mailMessage = new MimeMailMessage();
            mailMessage.From = new MimeMailAddress("3003110860@qq.com");
            mailMessage.To.Add("rob_sky@163.com") ;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Subject = "佳成系统通知!" + DateTime.Now.ToLongTimeString();
            if (Engine.Razor.IsTemplateCached("templateKey", null))
                Engine.Razor.Run("templateKey", null, mail.Content);
            else
                mailMessage.Body = Engine.Razor.RunCompile(template, "templateKey", null, mail.Content);

            //RazorEngine.Templating.RazorEngineService service = new RazorEngineService
            //Create Smtp Client
            var mailer = new MimeMailer("smtp.qq.com", 465)
            {
                User = "3003110860@qq.com",
                Password = "jogwuppsxqdsddbe",
                SslType = SslMode.Ssl,
                AuthenticationMode = AuthenticationType.Base64
            };

            //Set a delegate function for call back
            mailer.SendCompleted += Mailer_SendCompleted; ;
            //mailer.SendMailAsync(mailMessage);
            mailer.Send(mailMessage);
            return Ok();

        }

        private void Mailer_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs asynccompletedeventargs)
        {
            if (!String.IsNullOrEmpty(asynccompletedeventargs.UserState.ToString()))
                Console.WriteLine(asynccompletedeventargs.UserState.ToString());
            Console.Out.WriteLine("is it canceled? " + asynccompletedeventargs.Cancelled);

            if (asynccompletedeventargs.Error != null)
                Console.Out.WriteLine("Error : " + asynccompletedeventargs.Error.Message);
        }

        private async Task SendMail(string mailContent)
        {
            var credentialUserName = "3003110860@qq.com";
            var sentFrom = "3003110860@qq.com";
            var pwd = "jogwuppsxqdsddbe";

            System.Net.Mail.SmtpClient client =
                new System.Net.Mail.SmtpClient();
            client.Host = "smtp.qq.com";
            //client.Port = 465;//smtp邮件服务器端口
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;

            System.Net.NetworkCredential credentials =
                new System.Net.NetworkCredential(credentialUserName, pwd);

            client.EnableSsl = true;
            client.Credentials = credentials;

            var mail =
                new System.Net.Mail.MailMessage("LHX<3003110860@qq.com>", "rob_sky@163.com");

            mail.Subject = "测试邮件";
            mail.Body = mailContent;
            await client.SendMailAsync(mail);
        }
    }
}
/**
 * 模拟请求数据
User-Agent: Fiddler
Host: 192.168.10.152:8009
Content-Length: 131
Content-Type: application/json

{
  "To": ["xakml@qq.com"  ],
  "CC": ["rob_sky@163.com" ],
  "Subject": "主题",
  "Content": {"Name":"刘艳杰VS卢敏"}
}
    **/
// Razor Engine
//https://blog.csdn.net/xue251248603/article/details/77085486


//发送邮件参考地址:
// https://yeak2001.iteye.com/blog/859770
//https://www.cnblogs.com/reachteam/p/6481040.html
//https://www.cnblogs.com/xiezunxu/articles/7421322.html
//https://www.cnblogs.com/xiaofeixiang/archive/2014/05/21/3744015.html
//https://blog.csdn.net/qq_26744901/article/details/50069669

//保存已发送邮件到服务器发件箱
//https://service.mail.qq.com/cgi-bin/help?subtype=1&no=128&id=11

//使用AIM发送html格式的邮件
//https://blog.csdn.net/dsnq2011/article/details/72853598